package com.xdog.web3.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xdog.common.core.constant.GlobalConstants;
import com.xdog.common.core.utils.SpringUtils;
import com.xdog.common.redis.utils.RedisUtils;
import com.xdog.web3.domain.twitter.TwitterResponse;
import com.xdog.web3.domain.twitter.UnifiedTwitterData;
import com.xdog.web3.domain.twitter.TwitterFollowUser;
import com.xdog.web3.domain.twitter.TwitterTweetData;
import com.xdog.web3.domain.twitter.TwitterUserData;
import com.xdog.web3.mapper.twitter.TwitterFollowUserMapper;
import com.xdog.web3.mapper.twitter.TwitterTweetDataMapper;
import com.xdog.web3.mapper.twitter.TwitterUserDataMapper;
import com.xdog.web3.service.ITwitterService;
import com.xdog.web3.utils.TwitterAvatarDownloader;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Twitter服务实现类
 */
@Slf4j
@Service
public class TwitterServiceImpl implements ITwitterService {

    @Value("${twitter.api.key}")
    private String apiKey;

    private final TwitterFollowUserMapper twitterFollowUserMapper;

    private final TwitterAvatarDownloader twitterAvatarDownloader;

    private final TwitterTweetDataMapper twitterTweetDataMapper;

    private final TwitterUserDataMapper twitterUserDataMapper;

    public TwitterServiceImpl(TwitterFollowUserMapper twitterFollowUserMapper,
                              TwitterAvatarDownloader twitterAvatarDownloader,
                              TwitterTweetDataMapper twitterTweetDataMapper,
                              TwitterUserDataMapper twitterUserDataMapper) {
        this.twitterFollowUserMapper = twitterFollowUserMapper;
        this.twitterAvatarDownloader = twitterAvatarDownloader;
        this.twitterTweetDataMapper = twitterTweetDataMapper;
        this.twitterUserDataMapper = twitterUserDataMapper;
        // 移除 WebClient 使用 OkHttpClient
    }

    // Redis缓存键前缀
    private static final String TWITTER_CACHE_KEY_PREFIX = GlobalConstants.GLOBAL_REDIS_KEY + "twitter:data:";

    // 默认搜索关键词
    private static final String DEFAULT_KEYWORD = "xdog";

    // 默认返回推文数量
    private static final int DEFAULT_COUNT = 20;

    /**
     * 定时任务1：使用twitter293 API获取Twitter数据并缓存
     */
    @Scheduled(fixedRate = 150, timeUnit = TimeUnit.MINUTES, initialDelay = 150)
    public void fetchAndCacheTwitterData1() {
        log.info("开始执行Twitter数据定时获取任务1（twitter293 API）");
        try {
            // 使用twitter293 API获取Twitter数据
            TwitterResponse response = searchTweetsFromAPI1(DEFAULT_KEYWORD, DEFAULT_COUNT);

            // 将数据转换为统一格式并存储到Redis缓存中
            UnifiedTwitterData unifiedData = convertToUnifiedData(response, "api1");

            // 保存完整的Twitter数据到数据库
            saveAllTwitterDataToDatabase(unifiedData);

            String cacheKey = TWITTER_CACHE_KEY_PREFIX + DEFAULT_KEYWORD;

            // 检查UnifiedTwitterData是否有数据
            if (unifiedData != null && unifiedData.getTweets() != null && !unifiedData.getTweets().isEmpty()) {
                // 只有当UnifiedTwitterData有数据时才更新缓存
                RedisUtils.setCacheObject(cacheKey, unifiedData);
                log.info("Twitter数据定时获取任务1执行成功，数据已缓存至: {}", cacheKey);
            } else {
                log.info("Twitter数据定时获取任务1执行完成，但未获取到有效数据，不更新缓存");
            }
        } catch (Exception e) {
            log.error("Twitter数据定时获取任务1执行失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 定时任务2：使用twitter-x-api获取Twitter数据并缓存
     */
    @Scheduled(fixedRate = 500, timeUnit = TimeUnit.MINUTES, initialDelay = 500)
    public void fetchAndCacheTwitterData2() {
        log.info("开始执行Twitter数据定时获取任务2（twitter-x-api）");
        try {
            // 使用twitter-x-api获取Twitter数据
            TwitterResponse response = searchTweetsFromAPI2(DEFAULT_KEYWORD, DEFAULT_COUNT);

            // 将数据转换为统一格式并存储到Redis缓存中
            UnifiedTwitterData unifiedData = convertToUnifiedData(response, "api2");

            // 保存完整的Twitter数据到数据库
            saveAllTwitterDataToDatabase(unifiedData);

            String cacheKey = TWITTER_CACHE_KEY_PREFIX + DEFAULT_KEYWORD;

            // 检查UnifiedTwitterData是否有数据
            if (unifiedData != null && unifiedData.getTweets() != null && !unifiedData.getTweets().isEmpty()) {
                // 只有当UnifiedTwitterData有数据时才更新缓存
                RedisUtils.setCacheObject(cacheKey, unifiedData);
                log.info("Twitter数据定时获取任务2执行成功，数据已缓存至: {}", cacheKey);
            } else {
                log.info("Twitter数据定时获取任务2执行完成，但未获取到有效数据，不更新缓存");
            }
        } catch (Exception e) {
            log.error("Twitter数据定时获取任务2执行失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 定时任务3：使用real-time-x-com-data-scraper API获取Twitter数据并缓存
     */
    @Scheduled(fixedRate = 200, timeUnit = TimeUnit.MINUTES, initialDelay = 200)
    public void fetchAndCacheTwitterData3() {
        log.info("开始执行Twitter数据定时获取任务3（real-time-x-com-data-scraper API）");
        try {
            // 使用real-time-x-com-data-scraper API获取Twitter数据
            TwitterResponse response = searchTweetsFromAPI3(DEFAULT_KEYWORD, DEFAULT_COUNT);

            // 将数据转换为统一格式并存储到Redis缓存中
            UnifiedTwitterData unifiedData = convertToUnifiedData(response, "api3");

            // 保存完整的Twitter数据到数据库
            saveAllTwitterDataToDatabase(unifiedData);

            String cacheKey = TWITTER_CACHE_KEY_PREFIX + DEFAULT_KEYWORD;

            // 检查UnifiedTwitterData是否有数据
            if (unifiedData != null && unifiedData.getTweets() != null && !unifiedData.getTweets().isEmpty()) {
                // 只有当UnifiedTwitterData有数据时才更新缓存
                RedisUtils.setCacheObject(cacheKey, unifiedData);
                log.info("Twitter数据定时获取任务3执行成功，数据已缓存至: {}", cacheKey);
            } else {
                log.info("Twitter数据定时获取任务3执行完成，但未获取到有效数据，不更新缓存");
            }
        } catch (Exception e) {
            log.error("Twitter数据定时获取任务3执行失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 定时任务4：使用twitter135 API获取Twitter数据并缓存
     */
    @Scheduled(fixedRate = 435, timeUnit = TimeUnit.MINUTES, initialDelay = 435)
    public void fetchAndCacheTwitterData4() {
        log.info("开始执行Twitter数据定时获取任务4（twitter135 API）");
        try {
            // 使用twitter135 API获取Twitter数据
            TwitterResponse response = searchTweetsFromAPI4(DEFAULT_KEYWORD, DEFAULT_COUNT);

            // 将数据转换为统一格式并存储到Redis缓存中
            UnifiedTwitterData unifiedData = convertToUnifiedData(response, "api4");

            // 保存完整的Twitter数据到数据库
            saveAllTwitterDataToDatabase(unifiedData);

            String cacheKey = TWITTER_CACHE_KEY_PREFIX + DEFAULT_KEYWORD;

            // 检查UnifiedTwitterData是否有数据
            if (unifiedData != null && unifiedData.getTweets() != null && !unifiedData.getTweets().isEmpty()) {
                // 只有当UnifiedTwitterData有数据时才更新缓存
                RedisUtils.setCacheObject(cacheKey, unifiedData);
                log.info("Twitter数据定时获取任务4执行成功，数据已缓存至: {}", cacheKey);
            } else {
                log.info("Twitter数据定时获取任务4执行完成，但未获取到有效数据，不更新缓存");
            }
        } catch (Exception e) {
            log.error("Twitter数据定时获取任务4执行失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 从twitter293 API获取数据
     */
    private TwitterResponse searchTweetsFromAPI1(String keyword, int count) {
        try {
            // 使用OkHttpClient实现，不使用代理配置
            OkHttpClient client = new OkHttpClient();

            // 动态计算最近两天的日期
            java.time.LocalDate twoDaysAgo = java.time.LocalDate.now().minusDays(2);
            String sinceDate = twoDaysAgo.toString();
            String filters = java.net.URLEncoder.encode("{\"since\": \"" + sinceDate + "\"}", StandardCharsets.UTF_8);
            String url = String.format(
                "https://twitter293.p.rapidapi.com/search/%s?count=%d&category=Top&filters=%s",
                keyword,
                Math.min(count, 500),
                filters
            );

            Request request = new Request.Builder()
                .url(url)
                .get()
                .addHeader("x-rapidapi-key", "6f8baab884msha4821cee2751e7ep179713jsn84356a64ce01")
                .addHeader("x-rapidapi-host", "twitter293.p.rapidapi.com")
                .build();

            Response response = client.newCall(request).execute();

            if (response.body() != null) {
                String responseBody = response.body().string();
                return JSONObject.parseObject(responseBody, TwitterResponse.class);
            } else {
                throw new IOException("Response body is null");
            }
        } catch (Exception e) {
            log.error("从twitter293 API获取Twitter数据失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取Twitter数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 从twitter-x-api获取数据
     */
    private TwitterResponse searchTweetsFromAPI2(String keyword, int count) {
        try {
            // 使用OkHttpClient替换原来的WebClient实现，不使用代理配置
            OkHttpClient client = new OkHttpClient();

            String url = String.format(
                "https://twitter-x-api.p.rapidapi.com/api/search/people?keyword=%s&count=%d",
                keyword,
                Math.min(count, 500)
            );

            Request request = new Request.Builder()
                .url(url)
                .get()
                .addHeader("x-rapidapi-key", apiKey)
                .addHeader("x-rapidapi-host", "twitter-x-api.p.rapidapi.com")
                .build();

            Response response = client.newCall(request).execute();

            if (response.body() != null) {
                String responseBody = response.body().string();
                return JSONObject.parseObject(responseBody, TwitterResponse.class);
            } else {
                throw new IOException("Response body is null");
            }
        } catch (Exception e) {
            log.error("从twitter-x-api获取Twitter数据失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取Twitter数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 从real-time-x-com-data-scraper API获取数据
     */
    private TwitterResponse searchTweetsFromAPI3(String keyword, int count) {
        try {
            // 使用OkHttpClient实现，不使用代理配置
            OkHttpClient client = new OkHttpClient();

            String url = String.format(
                "https://real-time-x-com-data-scraper.p.rapidapi.com/Search/?safe_search=true&q=%s&count=%d",
                keyword,
                Math.min(count, 500)
            );

            Request request = new Request.Builder()
                .url(url)
                .get()
                .addHeader("x-rapidapi-key", "6f8baab884msha4821cee2751e7ep179713jsn84356a64ce01")
                .addHeader("x-rapidapi-host", "real-time-x-com-data-scraper.p.rapidapi.com")
                .build();

            Response response = client.newCall(request).execute();

            if (response.body() != null) {
                String responseBody = response.body().string();
                // 尝试解析JSON，如果失败则记录原始响应
                try {
                    return JSONObject.parseObject(responseBody, TwitterResponse.class);
                } catch (Exception parseException) {
                    log.error("解析Twitter API响应失败，原始响应内容: {}", responseBody);
                    throw new RuntimeException("解析Twitter数据失败: " + parseException.getMessage(), parseException);
                }
            } else {
                throw new IOException("Response body is null");
            }
        } catch (Exception e) {
            log.error("从real-time-x-com-data-scraper API获取Twitter数据失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取Twitter数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 从twitter135 API获取数据
     */
    private TwitterResponse searchTweetsFromAPI4(String keyword, int count) {
        try {
            // 使用OkHttpClient实现，不使用代理配置
            OkHttpClient client = new OkHttpClient();

            String url = String.format(
                "https://twitter135.p.rapidapi.com/Search/?q=%s&count=%d&type=Top&safe_search=true",
                keyword,
                Math.min(count, 500)
            );

            Request request = new Request.Builder()
                .url(url)
                .get()
                .addHeader("x-rapidapi-key", "6f8baab884msha4821cee2751e7ep179713jsn84356a64ce01")
                .addHeader("x-rapidapi-host", "twitter135.p.rapidapi.com")
                .build();

            Response response = client.newCall(request).execute();

            if (response.body() != null) {
                String responseBody = response.body().string();
                return JSONObject.parseObject(responseBody, TwitterResponse.class);
            } else {
                throw new IOException("Response body is null");
            }
        } catch (Exception e) {
            log.error("从twitter135 API获取Twitter数据失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取Twitter数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 将TwitterResponse转换为统一格式的UnifiedTwitterData
     * @param response 原始Twitter响应数据
     * @param sourceApi 数据来源API标识
     * @return 统一格式的Twitter数据
     */
    private UnifiedTwitterData convertToUnifiedData(TwitterResponse response, String sourceApi) {
        UnifiedTwitterData unifiedData = new UnifiedTwitterData();
        unifiedData.setSourceApi(sourceApi);
        unifiedData.setFetchTime(System.currentTimeMillis());

        // 处理推文数据
        List<UnifiedTwitterData.Tweet> unifiedTweets = new ArrayList<>();

        try {
            // 处理新的API结构 (twitter135 API)
            if (response.getData() != null &&
                response.getData().getSearch_by_raw_query() != null &&
                response.getData().getSearch_by_raw_query().getSearch_timeline() != null &&
                response.getData().getSearch_by_raw_query().getSearch_timeline().getTimeline() != null &&
                response.getData().getSearch_by_raw_query().getSearch_timeline().getTimeline().getInstructions() != null) {

                for (TwitterResponse.Instruction instruction : response.getData().getSearch_by_raw_query().getSearch_timeline().getTimeline().getInstructions()) {
                    if ("TimelineAddEntries".equals(instruction.getType()) && instruction.getEntries() != null) {
                        for (TwitterResponse.Entry entry : instruction.getEntries()) {
                            // 处理推文条目
                            if (entry.getContent() != null &&
                                entry.getContent().getItemContent() != null &&
                                entry.getContent().getItemContent().getTweet_results() != null &&
                                entry.getContent().getItemContent().getTweet_results().getResult() != null) {

                                TwitterResponse.TweetResult tweetResult = entry.getContent().getItemContent().getTweet_results().getResult();
                                if (tweetResult.getLegacy() != null) {
                                    TwitterResponse.Legacy legacy = tweetResult.getLegacy();

                                    UnifiedTwitterData.Tweet unifiedTweet = new UnifiedTwitterData.Tweet();
                                    unifiedTweet.setId(tweetResult.getRest_id());
                                    unifiedTweet.setText(legacy.getFull_text());
                                    unifiedTweet.setCreatedAt(legacy.getCreated_at());
                                    unifiedTweet.setLikeCount(legacy.getFavorite_count());
                                    unifiedTweet.setRetweetCount(legacy.getRetweet_count());
                                    unifiedTweet.setReplyCount(legacy.getReply_count());
                                    unifiedTweet.setQuoteCount(legacy.getQuote_count());

                                    if (tweetResult.getViews() != null) {
                                        try {
                                            unifiedTweet.setViewCount(Integer.parseInt(tweetResult.getViews().getCount()));
                                        } catch (NumberFormatException e) {
                                            unifiedTweet.setViewCount(0);
                                        }
                                    }

                                    // 处理用户信息
                                    if (tweetResult.getCore() != null &&
                                        tweetResult.getCore().getUser_results() != null &&
                                        tweetResult.getCore().getUser_results().getResult() != null) {

                                        TwitterResponse.Result userResult = tweetResult.getCore().getUser_results().getResult();
                                        if (userResult.getLegacy() != null) {
                                            TwitterResponse.Legacy userLegacy = userResult.getLegacy();

                                            UnifiedTwitterData.User unifiedUser = new UnifiedTwitterData.User();
                                            unifiedUser.setId(userResult.getRest_id());
                                            unifiedUser.setName(userLegacy.getName());
                                            unifiedUser.setScreenName(userLegacy.getScreen_name());
                                            unifiedUser.setProfileImageUrl(userLegacy.getProfile_image_url_https());
                                            unifiedUser.setFollowersCount(userLegacy.getFollowers_count());
                                            unifiedUser.setFollowingCount(userLegacy.getFriends_count());
                                            unifiedUser.setTweetsCount(userLegacy.getStatuses_count());
                                            unifiedUser.setDescription(userLegacy.getDescription());
                                            unifiedUser.setVerified(userLegacy.getVerified());

                                            unifiedTweet.setUser(unifiedUser);
                                        }
                                    }

                                    unifiedTweets.add(unifiedTweet);
                                }
                            }
                        }
                    }
                }
            }
            // 处理旧的复杂结构的数据 (twitter293 API)
            else if (response.getEntries() != null && !response.getEntries().isEmpty()) {
                // 处理复杂结构的数据 (twitter293 API)
                for (TwitterResponse.Entry entry : response.getEntries()) {
                    // 注意：这里使用的是旧的Entry结构，它有一个getEntries方法
                    // 但我们现在需要检查entry是否是旧的Entry类型（具有getEntries方法）
                    // 由于Java类型系统，我们需要通过字段存在性来判断

                    // 对于旧API结构，我们直接处理entry中的内容，而不是调用getEntries
                    if (entry.getContent() != null &&
                        entry.getContent().getItemContent() != null &&
                        entry.getContent().getItemContent().getTweet_results() != null) {

                        TwitterResponse.TweetResult tweetResult = entry.getContent().getItemContent().getTweet_results().getResult();
                        if (tweetResult != null && tweetResult.getLegacy() != null) {
                            TwitterResponse.Legacy legacy = tweetResult.getLegacy();

                            UnifiedTwitterData.Tweet unifiedTweet = new UnifiedTwitterData.Tweet();
                            unifiedTweet.setId(tweetResult.getRest_id());
                            unifiedTweet.setText(legacy.getFull_text());
                            unifiedTweet.setCreatedAt(legacy.getCreated_at());
                            unifiedTweet.setLikeCount(legacy.getFavorite_count());
                            unifiedTweet.setRetweetCount(legacy.getRetweet_count());
                            unifiedTweet.setReplyCount(legacy.getReply_count());
                            unifiedTweet.setQuoteCount(legacy.getQuote_count());

                            if (tweetResult.getViews() != null) {
                                try {
                                    unifiedTweet.setViewCount(Integer.parseInt(tweetResult.getViews().getCount()));
                                } catch (NumberFormatException e) {
                                    unifiedTweet.setViewCount(0);
                                }
                            }

                            // 处理用户信息
                            if (tweetResult.getCore() != null &&
                                tweetResult.getCore().getUser_results() != null &&
                                tweetResult.getCore().getUser_results().getResult() != null) {

                                TwitterResponse.Result userResult = tweetResult.getCore().getUser_results().getResult();
                                if (userResult.getLegacy() != null) {
                                    TwitterResponse.Legacy userLegacy = userResult.getLegacy();

                                    UnifiedTwitterData.User unifiedUser = new UnifiedTwitterData.User();
                                    unifiedUser.setId(userResult.getRest_id());
                                    unifiedUser.setName(userLegacy.getName());
                                    unifiedUser.setScreenName(userLegacy.getScreen_name());
                                    unifiedUser.setProfileImageUrl(userLegacy.getProfile_image_url_https());
                                    unifiedUser.setFollowersCount(userLegacy.getFollowers_count());
                                    unifiedUser.setFollowingCount(userLegacy.getFriends_count());
                                    unifiedUser.setTweetsCount(userLegacy.getStatuses_count());
                                    unifiedUser.setDescription(userLegacy.getDescription());
                                    unifiedUser.setVerified(userLegacy.getVerified());

                                    unifiedTweet.setUser(unifiedUser);
                                }
                            }

                            unifiedTweets.add(unifiedTweet);
                        }
                    }
                }
            }
            // 处理简化结构的数据 (twitter-x-api等)
            else if (response.getData() != null && response.getData().getData() != null && !response.getData().getData().isEmpty()) {
                for (TwitterResponse.TweetData tweetData : response.getData().getData()) {
                    UnifiedTwitterData.Tweet unifiedTweet = new UnifiedTwitterData.Tweet();
                    unifiedTweet.setId(tweetData.getId());
                    unifiedTweet.setText(tweetData.getText());
                    unifiedTweet.setCreatedAt(tweetData.getCreated_at());

                    if (tweetData.getPublic_metrics() != null) {
                        unifiedTweet.setLikeCount(tweetData.getPublic_metrics().getLike_count());
                        unifiedTweet.setRetweetCount(tweetData.getPublic_metrics().getRetweet_count());
                        unifiedTweet.setReplyCount(tweetData.getPublic_metrics().getReply_count());
                        unifiedTweet.setQuoteCount(tweetData.getPublic_metrics().getQuote_count());
                        unifiedTweet.setViewCount(tweetData.getPublic_metrics().getView_count());
                    }

                    // 处理用户信息
                    if (tweetData.getUser() != null) {
                        UnifiedTwitterData.User unifiedUser = new UnifiedTwitterData.User();
                        unifiedUser.setId(tweetData.getUser().getId());
                        unifiedUser.setName(tweetData.getUser().getName());
                        unifiedUser.setScreenName(tweetData.getUser().getUsername());
                        unifiedUser.setProfileImageUrl(tweetData.getUser().getProfile_image_url());

                        unifiedTweet.setUser(unifiedUser);
                    }

                    unifiedTweets.add(unifiedTweet);
                }
            }
            // 处理另一种简化结构
            else if (response.getTweetDataList() != null && !response.getTweetDataList().isEmpty()) {
                for (TwitterResponse.TweetData tweetData : response.getTweetDataList()) {
                    UnifiedTwitterData.Tweet unifiedTweet = new UnifiedTwitterData.Tweet();
                    unifiedTweet.setId(tweetData.getId());
                    unifiedTweet.setText(tweetData.getText());
                    unifiedTweet.setCreatedAt(tweetData.getCreated_at());

                    if (tweetData.getPublic_metrics() != null) {
                        unifiedTweet.setLikeCount(tweetData.getPublic_metrics().getLike_count());
                        unifiedTweet.setRetweetCount(tweetData.getPublic_metrics().getRetweet_count());
                        unifiedTweet.setReplyCount(tweetData.getPublic_metrics().getReply_count());
                        unifiedTweet.setQuoteCount(tweetData.getPublic_metrics().getQuote_count());
                        unifiedTweet.setViewCount(tweetData.getPublic_metrics().getView_count());
                    }

                    // 处理用户信息
                    if (tweetData.getUser() != null) {
                        UnifiedTwitterData.User unifiedUser = new UnifiedTwitterData.User();
                        unifiedUser.setId(tweetData.getUser().getId());
                        unifiedUser.setName(tweetData.getUser().getName());
                        unifiedUser.setScreenName(tweetData.getUser().getUsername());
                        unifiedUser.setProfileImageUrl(tweetData.getUser().getProfile_image_url());

                        unifiedTweet.setUser(unifiedUser);
                    }

                    unifiedTweets.add(unifiedTweet);
                }
            }
        } catch (Exception e) {
            log.error("解析Twitter数据时发生错误: {}", e.getMessage(), e);
        }

        unifiedData.setTweets(unifiedTweets);
        return unifiedData;
    }

    /**
     * 保存推荐用户数据到数据库并下载头像到OSS
     * @param unifiedData 统一格式的Twitter数据
     */
    public void saveRecommendedUsersToDatabase(UnifiedTwitterData unifiedData) {
        if (unifiedData == null || unifiedData.getUsers() == null || unifiedData.getUsers().isEmpty()) {
            return;
        }

        log.info("开始保存推荐用户数据到数据库，用户数量: {}", unifiedData.getUsers().size());

        for (UnifiedTwitterData.User user : unifiedData.getUsers()) {
            try {
                // 检查用户是否已存在
                TwitterFollowUser existingUser = twitterFollowUserMapper.selectById(user.getId());

                // 创建或更新用户信息
                TwitterFollowUser twitterFollowUser = new TwitterFollowUser();
                twitterFollowUser.setUserId(user.getId());
                twitterFollowUser.setName(user.getName());
                twitterFollowUser.setScreenName(user.getScreenName());
                twitterFollowUser.setProfileImageUrl(user.getProfileImageUrl());
                twitterFollowUser.setFollowersCount(user.getFollowersCount());
                twitterFollowUser.setFollowingCount(user.getFollowingCount());
                twitterFollowUser.setTweetsCount(user.getTweetsCount());
                twitterFollowUser.setDescription(user.getDescription());
                twitterFollowUser.setVerified(user.getVerified());
                twitterFollowUser.setProfileUrl("https://twitter.com/" + user.getScreenName());
                twitterFollowUser.setShow(1); // 默认显示

                // 下载并保存头像到OSS
                if (user.getProfileImageUrl() != null && !user.getProfileImageUrl().isEmpty()) {
                    String localAvatarPath = twitterAvatarDownloader.downloadAvatar(user.getProfileImageUrl(), user.getId());
                    if (localAvatarPath != null) {
                        twitterFollowUser.setLocalAvatarPath(localAvatarPath);
                    }
                }

                // 设置时间
                LocalDateTime now = LocalDateTime.now();
                twitterFollowUser.setUpdateTime(now);

                if (existingUser == null) {
                    // 新用户，插入数据
                    twitterFollowUser.setCreateTime(now);
                    twitterFollowUserMapper.insert(twitterFollowUser);
                    log.info("插入新用户: {}", user.getScreenName());
                } else {
                    // 已存在用户，更新数据
                    twitterFollowUserMapper.updateById(twitterFollowUser);
                    log.info("更新用户: {}", user.getScreenName());
                }
            } catch (Exception e) {
                log.error("保存用户数据时出错: userId={}, screenName={}", user.getId(), user.getScreenName(), e);
            }
        }

        log.info("推荐用户数据保存完成");
    }

    /**
     * 保存完整的Twitter数据到数据库（仅保存推文信息）
     * @param unifiedData 统一格式的Twitter数据
     */
    public void saveAllTwitterDataToDatabase(UnifiedTwitterData unifiedData) {
        if (unifiedData == null || unifiedData.getTweets() == null || unifiedData.getTweets().isEmpty()) {
            return;
        }

        log.info("开始保存完整的Twitter数据到数据库，数据来源: {}", unifiedData.getSourceApi());

        // 保存推文数据
        saveTweetsData(unifiedData);

        log.info("完整的Twitter数据保存完成");
    }

    /**
     * 保存推文数据到数据库
     * @param unifiedData 统一格式的Twitter数据
     */
    private void saveTweetsData(UnifiedTwitterData unifiedData) {
        if (unifiedData.getTweets() == null || unifiedData.getTweets().isEmpty()) {
            log.info("没有推文数据需要保存");
            return;
        }

        log.info("开始保存推文数据，推文数量: {}", unifiedData.getTweets().size());

        for (UnifiedTwitterData.Tweet tweet : unifiedData.getTweets()) {
            try {
                // 检查推文是否已存在
                TwitterTweetData existingTweet = twitterTweetDataMapper.selectOne(
                    new LambdaQueryWrapper<TwitterTweetData>()
                        .eq(TwitterTweetData::getTweetId, tweet.getId())
                        .eq(TwitterTweetData::getSourceApi, unifiedData.getSourceApi())
                );

                // 创建推文数据对象
                TwitterTweetData twitterTweetData = new TwitterTweetData();
                twitterTweetData.setTweetId(tweet.getId());
                twitterTweetData.setText(tweet.getText());
                twitterTweetData.setCreatedAt(tweet.getCreatedAt());
                twitterTweetData.setLikeCount(tweet.getLikeCount());
                twitterTweetData.setRetweetCount(tweet.getRetweetCount());
                twitterTweetData.setReplyCount(tweet.getReplyCount());
                twitterTweetData.setQuoteCount(tweet.getQuoteCount());
                twitterTweetData.setViewCount(tweet.getViewCount());
                twitterTweetData.setUrl(tweet.getUrl());
                twitterTweetData.setSourceApi(unifiedData.getSourceApi());

                // 设置用户ID（如果存在）
                if (tweet.getUser() != null) {
                    twitterTweetData.setUserId(tweet.getUser().getId());

                    // 同时保存用户数据
                    saveUserData(tweet.getUser(), unifiedData.getSourceApi());
                }

                // 设置时间
                LocalDateTime now = LocalDateTime.now();
                twitterTweetData.setUpdateTime(now);

                if (existingTweet == null) {
                    // 新推文，插入数据
                    twitterTweetData.setCreateTime(now);
                    twitterTweetDataMapper.insert(twitterTweetData);
                    log.info("插入新推文: {}", tweet.getId());
                } else {
                    // 已存在推文，更新数据
                    twitterTweetData.setId(existingTweet.getId());
                    twitterTweetDataMapper.updateById(twitterTweetData);
                    log.info("更新推文: {}", tweet.getId());
                }
            } catch (Exception e) {
                log.error("保存推文数据时出错: tweetId={}", tweet.getId(), e);
            }
        }

        log.info("推文数据保存完成");
    }

    /**
     * 保存单个用户数据到数据库
     * @param user 用户数据
     * @param sourceApi 数据来源API标识
     */
    private void saveUserData(UnifiedTwitterData.User user, String sourceApi) {
        try {
            // 检查用户是否已存在
            TwitterUserData existingUser = twitterUserDataMapper.selectOne(
                new LambdaQueryWrapper<TwitterUserData>()
                    .eq(TwitterUserData::getUserId, user.getId())
                    .eq(TwitterUserData::getSourceApi, sourceApi)
            );

            // 创建用户数据对象
            TwitterUserData twitterUserData = new TwitterUserData();
            twitterUserData.setUserId(user.getId());
            twitterUserData.setName(user.getName());
            twitterUserData.setScreenName(user.getScreenName());
            twitterUserData.setProfileImageUrl(user.getProfileImageUrl());
            twitterUserData.setFollowersCount(user.getFollowersCount());
            twitterUserData.setFollowingCount(user.getFollowingCount());
            twitterUserData.setTweetsCount(user.getTweetsCount());
            twitterUserData.setDescription(user.getDescription());
            twitterUserData.setVerified(user.getVerified());
            twitterUserData.setProfileUrl("https://twitter.com/" + user.getScreenName());
            twitterUserData.setSourceApi(sourceApi);

            // 下载并保存头像到OSS
            if (user.getProfileImageUrl() != null && !user.getProfileImageUrl().isEmpty()) {
                String localAvatarPath = twitterAvatarDownloader.downloadAvatar(user.getProfileImageUrl(), user.getId());
                if (localAvatarPath != null) {
                    twitterUserData.setLocalAvatarPath(localAvatarPath);
                }
            }

            // 设置时间
            LocalDateTime now = LocalDateTime.now();
            twitterUserData.setUpdateTime(now);

            if (existingUser == null) {
                // 新用户，插入数据
                twitterUserData.setCreateTime(now);
                twitterUserDataMapper.insert(twitterUserData);
                log.info("插入新用户: {}", user.getScreenName());
            } else {
                // 已存在用户，更新数据
                twitterUserData.setId(existingUser.getId());
                twitterUserDataMapper.updateById(twitterUserData);
                log.info("更新用户: {}", user.getScreenName());
            }
        } catch (Exception e) {
            log.error("保存用户数据时出错: userId={}, screenName={}", user.getId(), user.getScreenName(), e);
        }
    }

    @Override
    public UnifiedTwitterData getCachedTwitterData() {
        String cacheKey = TWITTER_CACHE_KEY_PREFIX + DEFAULT_KEYWORD;
        log.info("尝试从Redis获取缓存数据，键名: {}", cacheKey);

        // 获取Redisson客户端并检查配置
        try {
            RedissonClient redissonClient = SpringUtils.getBean(RedissonClient.class);
            if (redissonClient instanceof Redisson) {
                Redisson redisson = (Redisson) redissonClient;
                // 注意：这里可能无法直接访问内部配置，我们尝试通过其他方式确认
            }
        } catch (Exception e) {
            log.warn("无法获取Redisson客户端配置信息: ", e);
        }

        // 检查键是否存在
        boolean keyExists = RedisUtils.hasKey(cacheKey);
        log.info("检查键是否存在: {} 结果: {}", cacheKey, keyExists);

        if (!keyExists) {
            // 尝试列出所有可能的键
            try {
                Collection<String> allKeys = RedisUtils.keys("*");
                log.info("Redis中所有键的数量: {}", allKeys.size());

                // 查找可能匹配的键
                List<String> possibleMatches = allKeys.stream()
                    .filter(key -> key.contains("twitter") || key.contains("xdog"))
                    .collect(Collectors.toList());
                log.info("可能匹配的键: {}", possibleMatches);

                // 尝试更广泛的模式匹配
                Collection<String> keys1 = RedisUtils.keys("*xdog*");
                log.info("匹配*xdog*的键有: {}", keys1);

                Collection<String> keys2 = RedisUtils.keys("*twitter*");
                log.info("匹配*twitter*的键有: {}", keys2);
            } catch (Exception e) {
                log.error("列出键时出错: ", e);
            }
        }

        UnifiedTwitterData result = RedisUtils.getCacheObject(cacheKey);
        log.info("从Redis获取到的数据: {}", result != null ? "存在" : "不存在");
        if (result != null) {
            log.info("获取到的Twitter数据包含 {} 条推文", result.getTweets() != null ? result.getTweets().size() : 0);
        }
        return result;
    }

    @Override
    public List<TwitterFollowUser> getRecommendedTwitterUsers() {// 从数据库中获取推荐的Twitter用户，按粉丝数降序排列，限制10个（忽略多租户）
        return twitterFollowUserMapper.selectRecommendedUsers();
    }
}
